﻿using System;
using System.Globalization;
using System.Web.Mvc;
using ActivateYourGlutes.Controllers;
using ActivateYourGlutes.Model.Contracts;

namespace ActivateYourGlutes.Helpers
{
    public class LocalisedDateTimeBinder : IModelBinder
    {
        #region Implementation of IModelBinder

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {            
            var date = bindingContext.ValueProvider[bindingContext.ModelName].AttemptedValue;
            if (String.IsNullOrEmpty(date))
                return null;

            return BindDate(date, controllerContext, bindingContext).Value;
        }

        public DateTime? BindDate(string date, ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, bindingContext.ValueProvider[bindingContext.ModelName]);
            try
            {
                var locale = (UserLocaleSettings)controllerContext.HttpContext.Session[LocalisingController.LocaleSessionKey] ?? LocaleFactory.GetLocale(controllerContext.HttpContext);
                return DateTime.ParseExact(date, locale.DateFormat, CultureInfo.InvariantCulture);
            }
            catch (Exception)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, String.Format("\"{0}\" is invalid.", bindingContext.ModelName));
                return null;
            }
        }

        #endregion
    }
}
